package com.xiaoma.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoma.product.dao.CategoryDao;
import com.xiaoma.product.entity.CategoryEntity;
import com.xiaoma.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: xiaoma
 * @Date: 2021/7/9 10:03
 * @description:
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Override
    public List<CategoryEntity> queryAll2Tree() {
        //查出所有分类
        List<CategoryEntity> list = baseMapper.selectList(null);
        //筛选出一级分类
        List<CategoryEntity> res = list.stream().filter((categoryEntity) -> categoryEntity.getParentCid() == 0)
                //给当前分类的子分类Children属性赋值
                .map((categoryEntity) -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, list));
                    return categoryEntity;
                })
                .sorted((one, two) -> (one.getSort() == null ? 0 : one.getSort()) - (two.getSort() == null ? 0 : two.getSort()))
                .collect(Collectors.toList());
        return res;
    }

    @Override
    public Boolean removeMenuByIds(List<Long> idList) {
        //检查是否有子菜单
        for (Long id : idList) {
           QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
           queryWrapper.eq("cat_id",id);
           if (baseMapper.selectOne(queryWrapper).getCatLevel()!=3) return false;
        }
        //批量删除
        baseMapper.deleteBatchIds(idList);
        return true;
    }

    /**
     * @Description  在当前list中递归找出目标分类的子分类
     * @Author Xiaoma
     * @Date 2021/8/18 17:35
     * @param categoryEntity
     * @param list
     * @return java.util.List<com.xiaoma.product.entity.CategoryEntity>
     **/
    private List<CategoryEntity> getChildren(CategoryEntity categoryEntity, List<CategoryEntity> list) {
        List<CategoryEntity> res = list.stream()
                //集合中的父分类id等于该分类的id
                .filter((temp) -> temp.getParentCid().equals(categoryEntity.getCatId()))
                //将子分类的子分类属性也填充
                .map((temp) -> {
                    temp.setChildren(getChildren(temp, list));
                    return temp;
                })
                //排序
                .sorted((one, two) -> (one.getSort() == null ? 0 : one.getSort()) - (two.getSort() == null ? 0 : two.getSort()))
                .collect(Collectors.toList());
        return res;
    }
}
